import os
from src.formats.ESRIBundle.MapCache import *
def getSrcPath():
    return os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

# BundleBundlx管理类
class BundleBundlxManager:
    def __init__(self, filePath):
        self.srcPath = getSrcPath()
        self.filePath = filePath

        self.layerPath = '/Layers'

        self.XMLStringPath = self.filePath + '/' + self.layerPath + '/conf.xml'
        self.CDIStringPath = self.filePath + '/' + self.layerPath + '/conf.cdi'
        self.tileLayerInfo = self.readTileLayerInfo()
        self.WMTSCapabilities = self.readWMTSCapabilities()
        self.TMSRootXML = self.readTMSRootXML()
        self.TMSBasemapXML = self.readTMSBasemapXML()
        self.TMSTIlemapserviceXML = self.readTMSTilemapserviceXML()


    def readTileLayerInfo(self):
        with open(self.XMLStringPath, encoding='utf-8') as f1 ,open(self.CDIStringPath, encoding='utf-8') as f2:
            xml = bytes(f1.read().encode('utf-8'))
            cdi = bytes(f2.read().encode('utf-8'))
            return CacheInfo.ReadFromXMLString(xml, cdi)

    # 直接返回图片数据
    def getTileFromLRC(self, level, row, column):
        bundlPre = judgeSubBundle(row, column)
        bundlePath = self.filePath + '/' + self.layerPath + '/_alllayers/L' + str(int(level)).zfill(2) + '/' + bundlPre + '.bundle'
        bundlxPath = self.filePath + '/' + self.layerPath + '/_alllayers/L' + str(int(level)).zfill(2) + '/' + bundlPre + '.bundlx'

        with open(bundlePath, 'rb') as bundle, open(bundlxPath, 'rb') as bundlx:
            bundleFile = bundle.read()
            bundlxFile = bundlx.read()

        img = explodeTileInBundleWithBundlxFromBytesV1(row, column, bundlPre, bundleFile, bundlxFile,self.tileLayerInfo.cacheStorageInfo.packetSize)
        return {
            "level": level,
            "row": row,
            "column": column,
            "imgData": img
        }

    def readWMTSCapabilities(self):
        path = self.srcPath + '/conf/wmts/getcapabilities.xml'
        with open(path, encoding='utf-8') as f:
            obj = f.read()
            return obj

    def readTMSRootXML(self):
        path = self.srcPath + '/conf/tms/root.xml'
        with open(path, encoding='utf-8') as f:
            obj = f.read()
            return obj

    def readTMSBasemapXML(self):
        path = self.srcPath + '/conf/tms/basemap.xml'
        with open(path, encoding='utf-8') as f:
            obj = f.read()
            return obj

    def readTMSTilemapserviceXML(self):
        path = self.srcPath + '/conf/tms/tilemapservice.xml'
        with open(path, encoding='utf-8') as f:
            obj = f.read()
            return obj
